package com.andova.toolkit.net.oss;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.andova.net.upload.BaseUploadFile;
import com.andova.net.upload.UploadBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import androidx.annotation.NonNull;

import static com.andova.net.upload.UploadType.UPLOAD_TYPE_FLAG_FILE;

/**
 * Created by Administrator on 2017-09-18.
 * <p>后续可使用泛型</p>
 *
 * @author kzaxil
 * @since 1.0.0
 */
public class OssUploadFile extends BaseUploadFile implements OSSCompletedCallback<PutObjectRequest, PutObjectResult> {
    private String objectName;
    private String endpoint;
    private OssUploadClient oss;
    private OSSCredentialProvider credentialProvider;

    private Context applicationContext;

    public OssUploadFile(Context context) {
        if (context instanceof Application) {
            applicationContext = context;
        } else {
            applicationContext = context.getApplicationContext();
        }
        endpoint = "https://oss-cn-qingdao.aliyuncs.com";
        credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIQWCTRBo7lVY3", "cqzDQqcDkcSm72YkJqvgtb1cIGT7a4");
    }

    /**
     * 获得url链接
     */
    private synchronized String getUrl(OSS oss, String objectName) {
        // 生成URL
        return oss.presignPublicObjectURL("picasso-dev", objectName);
    }

    @Override
    public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
        UploadBean uploadBean = new UploadBean();
        uploadBean.url = getUrl(oss, objectName);
        uploadSuccess(UPLOAD_TYPE_FLAG_FILE, uploadBean);
    }

    @Override
    public void onFailure(PutObjectRequest putObjectRequest, ClientException clientException, ServiceException serviceException) {
        // 请求异常
        if (clientException != null) {
            uploadFail(clientException, putObjectRequest == null ? null : putObjectRequest.getUploadFilePath());
            // 本地异常如网络异常等
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            uploadFail(serviceException, putObjectRequest == null ? null : putObjectRequest.getUploadFilePath());
            // 服务异常
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }

    @Override
    protected void upload(@NonNull UploadBean uploadBean) {
        // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的访问控制章节
        if (oss == null) {
            oss = new OssUploadClient(applicationContext, endpoint, credentialProvider);
        }
        // 构造上传请求
        objectName = objectName();

        PutObjectRequest request = new PutObjectRequest("picasso-dev", objectName, uploadBean.url);
        oss.asyncPutObject(request, OssUploadFile.this);
    }

    @Override
    protected void upload(@NonNull byte[] uploadBytes) {
        // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的访问控制章节
        if (oss == null) {
            oss = new OssUploadClient(applicationContext, endpoint, credentialProvider);
        }
        // 构造上传请求
        objectName = objectName();

        PutObjectRequest request = new PutObjectRequest("picasso-dev", objectName, uploadBytes);
        oss.asyncPutObject(request, OssUploadFile.this);
    }

    @Override
    protected boolean exception(Throwable throwable) {
        return true;
    }

    private String objectName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        String time = format.format(new Date());

        return time + "-" + createUUID36() + ".jpg";//图片名称
    }

    // like 550E8400-E29B-11D4-A716-446655440000
    private String createUUID36() {
        return UUID.randomUUID().toString();
    }
}
